/**
 * @NApiVersion 2.x
 * @NScriptType Restlet
 * @NModuleScope SameAccount
 */
define(['N/http', 'N/https', 'N/record', 'N/search', 'N/runtime'],
/**
 * @param {http} http
 * @param {https} https
 * @param {record} record
 * @param {search} search
 */
function(http, https, record, search,runtime) {
   
   
    /**
     * Function called upon sending a GET request to the RESTlet.
     *
     * @param {Object} requestParams - Parameters from HTTP request URL; parameters will be passed into function as an Object (for all supported content types)
     * @returns {string | Object} HTTP response body; return string when request Content-Type is 'text/plain'; return Object when request Content-Type is 'application/json'
     * @since 2015.1
     */
    function doGet(requestParams) {

    }

    /**
     * Function called upon sending a PUT request to the RESTlet.
     *
     * @param {string | Object} requestBody - The HTTP request body; request body will be passed into function as a string when request Content-Type is 'text/plain'
     * or parsed into an Object when request Content-Type is 'application/json' (in which case the body must be a valid JSON)
     * @returns {string | Object} HTTP response body; return string when request Content-Type is 'text/plain'; return Object when request Content-Type is 'application/json'
     * @since 2015.2
     */
    function doPut(requestBody) {

    }
   
    /**
     * Function called upon sending a POST request to the RESTlet.
     *
     * @param {string | Object} requestBody - The HTTP request body; request body will be passed into function as a string when request Content-Type is 'text/plain'
     * or parsed into an Object when request Content-Type is 'application/json' (in which case the body must be a valid JSON)
     * @returns {string | Object} HTTP response body; return string when request Content-Type is 'text/plain'; return Object when request Content-Type is 'application/json'
     * @since 2015.2
     */
    function doPost(requestBody) {
    	
    	
    	
    	log.error({
			title : '请求正文.',
			details : 'requestBody: ' + JSON.stringify(requestBody)
		});
    	var resultJson = {
    			 "status": "300",
			     "errMessage": "",
    			 "data": ""
    	};
    	
		try {
			var jud = judgeField(requestBody);
			if(jud.length > 0){
				resultJson.status = '900';
				resultJson.errorMessage = jud;
				log.debug('e',e);
				log.debug('resultJson',resultJson);
				return resultJson;

			}
			var fin = createPayment(requestBody);
			if(isNaN(fin) == true){
				resultJson.status = '900';
				resultJson.errorMessage = fin;
				return resultJson;
			}
			var billrecord = record.load({type:'vendorpayment',id:fin});
			var number_text = billrecord.getValue('transactionnumber');
			resultJson.nsInternalid = fin
			resultJson.transactionnumber = number_text
			return resultJson
		}
			
		 catch (e) {
			// TODO: handle exception
			resultJson.status = '900';
			resultJson.errorMessage = e.message;
			log.debug('e',e);
			log.debug('resultJson',resultJson);
			return resultJson;
		}
		
		
		

    }

    /**
     * Function called upon sending a DELETE request to the RESTlet.
     *
     * @param {Object} requestParams - Parameters from HTTP request URL; parameters will be passed into function as an Object (for all supported content types)
     * @returns {string | Object} HTTP response body; return string when request Content-Type is 'text/plain'; return Object when request Content-Type is 'application/json'
     * @since 2015.2
     */
    function doDelete(requestParams) {

    }
	function judgeField(requsetBody){//判断必填字段是否有空
    	var err_mssage = []
    	if(requsetBody.payee== '' || requsetBody.payee == null){
			err_mssage.push('payee字段不能为空')
		}
		if(requsetBody.subsidiary== '' || requsetBody.subsidiary == null){
			err_mssage.push('subsidiary字段不能为空')
		}
		if(requsetBody.account== '' || requsetBody.account == null){
			err_mssage.push('account字段不能为空')
		}
		if(requsetBody.currency== '' || requsetBody.currency == null){
			err_mssage.push('currency字段不能为空')
		}
		if(requsetBody.exchangerate== '' || requsetBody.exchangerate == null){
			err_mssage.push('exchangerate字段不能为空')
		}
		if(requsetBody.date== '' || requsetBody.date == null){
			err_mssage.push('date字段不能为空')
		}
		if(requsetBody.applies == '' || requsetBody.applies ==null){
			err_mssage.push('applies字段不能为空')

		}
		return err_mssage;
	}
    function createPayment(requsetBody){
    	var billpayment = record.create({type:'vendorpayment',isDynamic: true})
		billpayment.setValue('entity',requsetBody.payee);
		// billpayment.setValue('entity',6105);
		billpayment.setValue('subsidiary',requsetBody.subsidiary);
		log.debug('account',requsetBody.account)
		var curid = getCurrencyId(requsetBody.currency);//获取currency的internalid
		if(curid == -1001){//如果返回-1001 代表不存在次货币
			resultJson.status = '900';
			resultJson.errorMessage = '不存在该货币类型。';
			log.debug('resultJson',resultJson);
			return resultJson;
		}
		billpayment.setValue('currency',curid);
		billpayment.setValue('exchangerate',requsetBody.exchangerate);
		billpayment.setValue('trandate',getDateformat(requsetBody.date));
		log.debug('cheque',requsetBody.cheque)
		billpayment.setValue('memo',requsetBody.memo);
		billpayment.setValue('account',requsetBody.account);
		var getac = billpayment.getValue('account');
		log.debug('getac',getac)
		var ap_apacct = getVendorap(requsetBody.payee)
		billpayment.setValue('apacct',ap_apacct);
		log.debug('ap_apacct',ap_apacct)
		var detail = requsetBody.applies;
		var appline = billpayment.getLineCount('apply');
		log.debug('appline',appline);
		billpayment.setValue('tranid',requsetBody.cheque);
		var line_err = [];
		for(var ap_i = 0;ap_i < appline;ap_i++){
			var line_apply = billpayment.selectLine({ sublistId: 'apply',line: ap_i})
			var transaction_line_id = line_apply.getCurrentSublistValue({sublistId: 'apply',fieldId: 'internalid'})
			// log.debug('transaction_line_id',transaction_line_id);

			var amt_due = line_apply.getCurrentSublistValue({sublistId: 'apply',fieldId: 'due'})
			for(var de_i = 0;de_i < detail.length;de_i++){
				var de_applise = detail[de_i].appliesto;
				// log.debug('de_applise',de_applise);

				var de_apply_amount = detail[de_i].payment;
				if(Number(de_applise) == Number(transaction_line_id)){
					if(Number(de_apply_amount) <= Number(amt_due)){
						// log.debug('de_apply_amount',de_apply_amount);

						line_apply.setCurrentSublistValue({sublistId: 'apply',fieldId: 'apply',value: true})
						line_apply.setCurrentSublistValue({sublistId: 'apply',fieldId: 'amount',value: de_apply_amount})
						// line_apply.commitLine({sublistId:'apply'})
					}else{
						var errmssage = 'internalid:'+de_applise+"可核销金额为："+amt_due;
						line_err.push(errmssage)
					}
					break;
				}
			}
		}
		if(line_err.length > 0){
			return line_err
		}
		log.debug('billpayment',billpayment)
		var savestar = new Date().getTime()
		var paymentid = billpayment.save()
		var saveend = new Date().getTime()
		log.debug('save',(savestar - saveend)/1000)
		return paymentid

	}
	function getDateString(offsethour){
		var now = new Date(offsethour);
		var moffset = now.getTimezoneOffset();
		var t  = new Date(now.getTime() + ((8 * 60 + moffset) * 60 * 1000));
		//var t = new Date(now.getTime() + (offsethour * 60 * 60 * 1000));
		var year = t.getFullYear();
		var month = t.getMonth() + 1;
		var day = t.getDate();
		var hour = t.getHours();
		var minute = t.getMinutes();
		var second = t.getSeconds();

		month = month < 10 ? '0' + month : month;
		day = day < 10 ? '0' + day : day;
		hour = hour < 10 ? '0' + hour : hour;
		minute = minute < 10 ? '0' + minute : minute;
		second = second < 10 ? '0' + second : second;

		return year + '/' + month + '/' + day;
	}
	function getDateformat(offsethour){
		var now = new Date(offsethour);
		var moffset = now.getTimezoneOffset();
		var t  = new Date(now.getTime() + ((8 * 60 + moffset) * 60 * 1000));
		//var t = new Date(now.getTime() + (offsethour * 60 * 60 * 1000));
		return t
	}
	function getCurrencyId(crname){
		var inv_filter1=[];
		var column=[];
		inv_filter1.push(search.createFilter({
			name: 'name',
			operator:search.Operator.IS,
			values:crname
		}));

		column.push(search.createColumn({name:'internalid'}));
		var cursearch = search.create({
			type:'currency',
			filters:inv_filter1,
			columns:column
		})
		var curresult = cursearch.run().getRange({start:0,end:5});
		var itemonhand_arr = []
		if(curresult && curresult.length > 0){
			return curresult[0].getValue('internalid')
		}
		return -1001;
	}
	function getVendorap(vendor){
    	var starttime = new Date().getTime();
		if(vendor){
			try {
				var vendorrecord = record.load({
					type:'vendor',
					id:vendor
				});
				var vendoraccount = vendorrecord.getValue('payablesaccount');
				log.debug('vendoraccount',vendoraccount)
				var endtime = new Date().getTime();
				var time = (endtime - starttime)/1000
				log.debug('time',time)
				return vendoraccount
			} catch (e) {
				// TODO: handle exception
				log.error('e',e);
			}

		}
	}

    return {
        'get': doGet,
        put: doPut,
        post: doPost,
        'delete': doDelete
    };
    
});
